package com.concurrent.threads.bank;

import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Bank
 * @Description TODO
 * @Author li
 * Date 2021/8/21 22:12
 * Copyright
 **/
public class Bank {

    private final double[] accounts;
    private final ReentrantLock reentrantLock = new ReentrantLock();

    /**
     * Constructs the bank
     * @param n the number of accounts
     * @param initial the initial balance of each account
     */
    public Bank(int n, double initial) {
        accounts = new double[n];
        Arrays.fill(accounts, initial);
    }

    /**
     * Gets the sum of all account money
     * @return the total money
     */
    public double totalBalance() {
        double sum = 0;
        for (double item :
                accounts) {
            sum += item;
        }
        return sum;
    }

    /**
     * transfer money from one account to another
     * @param from  the account to transfer from
     * @param to  the account to transfer to
     * @param val the amount of transfer
     */
    public void transfer(int from, int to, double val) {
        reentrantLock.lock();
        try {
//            if (accounts[from]< val){
//                System.out.println("this account money is not enough");
//                           return;
//            }
            System.out.println(Thread.currentThread());
            // 非原子操作,多线程同时操作时，会导致金额出现问题
            //        synchronized (this){
            //            accounts[from] -= val;
            //            accounts[to] += val;
            //        }
            accounts[from] -= val;
            accounts[to] += val;
            System.out.printf("%10.2f from %d to %d%n",val,from,to);
            System.out.printf("now,the total money of all account is %10.2f%n",totalBalance());
        }finally {
            reentrantLock.unlock();
        }

    }

    /**
     * get the number of accounts
     * @return the number of accounts
     */
    public int size(){
        return accounts.length;
    }
}
